package com.youdianda.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youdianda.constant.MessageConstant;
import com.youdianda.context.BaseContext;
import com.youdianda.dto.*;
import com.youdianda.entity.YddArticle;
import com.youdianda.entity.YddUser;
import com.youdianda.entity.YddUserData;
import com.youdianda.mapper.YddArticleMapper;
import com.youdianda.mapper.YddUserDataMapper;
import com.youdianda.mapper.YddUserMapper;
import com.youdianda.result.Result;
import com.youdianda.service.IYddArticleService;
import com.youdianda.service.IYddUserDataService;
import com.youdianda.service.IYddUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youdianda.utils.JwtUtil;
import com.youdianda.vo.GetUserInfoVO;
import com.youdianda.vo.Token;
import com.youdianda.vo.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sdy
 * @since 2023-05-15
 */
@Service
public class YddUserServiceImpl extends ServiceImpl<YddUserMapper, YddUser> implements IYddUserService {


    @Autowired
    private YddUserMapper userMapper;

    @Autowired
    private IYddUserDataService userDataService;
    @Autowired
    private IYddArticleService articleService;

    @Autowired
    private YddArticleMapper articleMapper;


    @Autowired
    private YddUserDataMapper userDataMapper;



    /**
     * 登录
     *
     * @param loginDTO
     * @return
     */
    @Override
    public Result login(UserLoginDTO loginDTO) {

        //1.判断用户是否存在

        YddUser user = getOne(Wrappers.<YddUser>lambdaQuery().eq(YddUser::getMobile, loginDTO.getMobile()),loginDTO!=null);
        if (user==null){
            return Result.error(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //密码加密
        loginDTO.setPassword(DigestUtils.md5DigestAsHex(loginDTO.getPassword().getBytes()));

        //2.判断密码是否正确
        if (!user.getPassword().equals(loginDTO.getPassword())){
            return Result.error(MessageConstant.PASSWORD_ERROR);
        }
        //3.生成token
        String token = JwtUtil.getToken(Long.parseLong(user.getId() + ""));

        return Result.success(Token.builder().token(token).build());
    }

    /**
     * 用户登录getUserInfo
     *
     * @return
     */
    @Override
    public Result getUserInfo() {

        //1.articleNum
        long articleNum = articleService.count();

        //collectNum
        List<YddUserData> listById = userDataService.list(Wrappers.<YddUserData>lambdaQuery().eq(YddUserData::getUserId, BaseContext.getCurrentId()));
        int collectNum = (int) listById.stream().filter(yddUserData -> yddUserData.getType() == 1).count();

        //userInfo
        YddUser userInfo = getOne(Wrappers.<YddUser>lambdaQuery().eq(YddUser::getId, BaseContext.getCurrentId()));

        //zanNum
        int zanNum = (int) listById.stream().filter(yddUserData -> yddUserData.getType() == 2).count();

        return Result.success(GetUserInfoVO.builder()
                .articleNum((int) articleNum)
                .collectNum(collectNum)
                .userInfo(userInfo)
                .zanNum(zanNum)
                .build());
    }

    /**
     * 用户详情
     *
     * @return
     */
    @Override
    public Result<YddUser> rowInfo(Integer id) {

        //非空判断
        if (id == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        YddUser user = getOne(Wrappers.<YddUser>lambdaQuery().eq(YddUser::getId, id));
        user.setPassword("******");

        return Result.success(user);
    }

    /**
     * 用户列表
     *
     * @return
     */
    @Override
    public Result UserList(UserListDTO userListDTO) {

        //非空判断
        if (userListDTO == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        //分页查询数据
//        IPage<YddUser> pageHelp = new Page<>(Long.parseLong(userListDTO.getPage()+""),Long.parseLong(userListDTO.getLimit()+""));
//        LambdaQueryWrapper<YddUser> queryWrapper = Wrappers.lambdaQuery();
//        queryWrapper.like(userListDTO.getSex()!=null,YddUser::getSex,userListDTO.getSex())
//                .like(userListDTO.getMobile()!=null,YddUser::getMobile,userListDTO.getMobile())
//                .like(userListDTO.getUsername()!=null,YddUser::getUsername,userListDTO.getUsername());
//
//        IPage<YddUser> page = userMapper.selectPage(pageHelp, queryWrapper);
//

//        list(Wrappers.<YddUser>lambdaQuery()
//                .like(userListDTO.getSex()!=null,YddUser::getSex,userListDTO.getSex())
//                .like(userListDTO.getMobile()!=null,YddUser::getMobile,userListDTO.getMobile())
//                .like(userListDTO.getUsername()!=null,YddUser::getUsername,userListDTO.getUsername())
//                );


        Page<YddUser> pageHelp = new Page<>(Long.parseLong(userListDTO.getPage() + ""), Long.parseLong(userListDTO.getLimit() + ""));
        Page<YddUser> page = page(pageHelp, Wrappers.<YddUser>lambdaQuery()
                .eq(userListDTO.getSex() != null && userListDTO.getSex() != "", YddUser::getSex, userListDTO.getSex())
                .like(userListDTO.getMobile() != null  && userListDTO.getMobile() != "", YddUser::getMobile, userListDTO.getMobile())
                .like(userListDTO.getUsername() != null && userListDTO.getUsername() != "", YddUser::getUsername, userListDTO.getUsername())
                .orderByDesc(YddUser::getId));




        //封装数据
//        List<aaaaa> list = new ArrayList<>();
//        page.getRecords().forEach(p->{
//            aaaaa aaaaa = new aaaaa();
//            BeanUtils.copyProperties(p,aaaaa);
//            list.add(aaaaa);
//        });

        //返回数据

        return Result.success(PageResult.builder()
                .count((int) page.getTotal())
                .totalPages((int) page.getPages())
                .pageSize((int) page.getSize())
                .currentPage((int) page.getCurrent())
                .data(page.getRecords())
                .build());
    }

    /**
     * 用户添加
     *
     * @param userAddDTO
     * @return
     */
    @Override
    public Result YddUserAdd(YddUserAddDTO userAddDTO) {

        //1.非空判断
        if (userAddDTO.getUsername()==null){
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        //2.用户名是否已存在
        if (getOne(Wrappers.<YddUser>lambdaQuery().eq(YddUser::getUsername,userAddDTO.getUsername()))!=null){
            return Result.error(MessageConstant.ACCOUNT_LOCKED);
        }

        //加密密码
        userAddDTO.setPassword(DigestUtils.md5DigestAsHex(userAddDTO.getPassword().getBytes()));
        //3.添加数据
        YddUser yddUser = new YddUser();
        BeanUtils.copyProperties(userAddDTO,yddUser);
        yddUser.setDefaultData("1");
        //添加
        save(yddUser);
        //4.返回数据
        return Result.success();
    }

    /**
     * 用户删除
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public Result del(Integer id) {

        //根据id删除
        removeById(id);
        //查询articleId并删除
//        YddUserData yddUserData = userDataMapper.selectOne(Wrappers.<YddUserData>lambdaQuery().eq(YddUserData::getUserId, id));
//       if (yddUserData==null){
//           return Result.error(MessageConstant.UNKNOWN_ERROR);
//       }
//        Integer id1 = yddUserData.getId();
//        userDataMapper.deleteById(id1);
//        //删除yddAricle
//        articleMapper.delete(Wrappers.<YddArticle>lambdaQuery().eq(YddArticle::getUserId,id));

        return Result.success();
    }

    /**
     * 用户修改
     *
     * @param userUpdateDTO
     * @return
     */
    @Override
    public Result updateYddUser(YddUserUpdateDTO userUpdateDTO) {

        //1.查询是否有已存在用户名
        if (getOne(Wrappers.<YddUser>lambdaQuery().eq(YddUser::getUsername,userUpdateDTO.getUsername()))!=null){
            return Result.error(MessageConstant.USERNAME_IS_FOUND);
        }
        //2.修改用户数据
        YddUser yddUser = new YddUser();
        BeanUtils.copyProperties(userUpdateDTO,yddUser);
        update(yddUser,Wrappers.<YddUser>lambdaQuery().eq(YddUser::getId,userUpdateDTO.getId()));
        //3.返回数据

        return Result.success();
    }

    /**
     * 修改用户资料
     *
     * @param updateUserDTO
     * @return
     */
    @Override
    public Result updateUser(UpdateUserDTO updateUserDTO) {


        //2.修改用户数据
        YddUser yddUser = new YddUser();
        BeanUtils.copyProperties(updateUserDTO,yddUser);
        update(yddUser,Wrappers.<YddUser>lambdaQuery().eq(YddUser::getId,updateUserDTO.getId()));
        //3.返回数据

        return Result.success();

    }
}
